﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace AuthorizationApiSample.Handlers
{
    /// <summary>
    /// 角色权限处理
    /// </summary>
    public class RolePermissionsHandler : AuthorizationHandler<RolePermissionsRequirement>
    {
        private readonly ILogger<RolePermissionsHandler> _logger;

        public RolePermissionsHandler(ILogger<RolePermissionsHandler> logger)
        {
            this._logger = logger;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolePermissionsRequirement requirement)
        {
            if (context.User.Identity.IsAuthenticated)
            {//有token并且已校验通过
                if (context.Resource is Microsoft.AspNetCore.Routing.RouteEndpoint)
                {
                    var route = context.Resource as Microsoft.AspNetCore.Routing.RouteEndpoint;
                    //TODO: 判断是否有权限
                    // route.RoutePattern.Defaults["action"]
                    // route.RoutePattern.Defaults["controller"]
                    this._logger.LogDebug($"{route.RoutePattern}");
                }
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
            return Task.CompletedTask;
        }
    }
}
